package com.totcy.atom.view.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.MenuItem;
import android.view.View;

import com.totcy.atom.R;
import com.totcy.atom.bean.AppVersion;
import com.totcy.atom.presenter.CheckUpdatePresenter;
import com.totcy.atom.presenter.contract.CheckUpdateContract;
import com.totcy.atom.view.fragment.HomeImageFragment;
import com.totcy.atom.view.fragment.HomeMineFragment;
import com.totcy.atom.view.fragment.HomeNewsTypeFragment;
import com.totcy.atom.view.fragment.RuankaoFragment;
import com.totcy.atom.view.fragment.WidgetFragment;
import com.totcy.baselibrary.base.BaseMvpActivity;
import com.totcy.baselibrary.manage.AppManager;
import com.totcy.baselibrary.utils.StatusBarUtil;
import com.totcy.baselibrary.utils.ToastUtil;
import com.totcy.baselibrary.widget.ProgressCircleView;

import org.datatist.sdk.autotrack.annotation.DatatistIgnoreTrackAppViewScreen;

import java.io.File;

import cn.jzvd.Jzvd;


/**
 * description: 主界面
 *
 * @author : Totcy
 * date: 2017/10/30 14:55
 * update: 2017/10/30
 */
@DatatistIgnoreTrackAppViewScreen
public class MainActivity extends BaseMvpActivity<CheckUpdateContract.View, CheckUpdatePresenter> implements BottomNavigationView.OnNavigationItemSelectedListener, CheckUpdateContract.View {

    private int currentMenuId = -1;
    BottomNavigationView navigation;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TabFragment.onDestroy();
    }

    @Override
    protected void startInvoke(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        //打开沉浸式模式 每个fragment自己适配 toolbar
        StatusBarUtil.immersive(this);

        navigation = findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(this);
        navigation.setSelectedItemId(R.id.navigation_ruankao);
        //去除超过四个移动动画
        //BottomNavigationViewHelper.disableShiftMode(navigation);

        //super already added。
        //AppManager.getInstance().addActivity(this);

        //版本更新检查
        getPresenter().doCheckUpdate();
    }


    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        if (currentMenuId == item.getItemId()) {
            return true;
        }
/*
        if (item.getItemId() == R.id.navigation_weather) {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                navigation.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.gray_6c));

                Animator animator1 = null;
                int cenX = navigation.getWidth() * 2 / 3;
                int cenY = navigation.getHeight() / 2;
                animator1 = ViewAnimationUtils.createCircularReveal(navigation, cenX, cenY, 0,
                        (float) Math.hypot(navigation.getWidth(), navigation.getHeight()));//宽的平方加上高的平方的根号
                animator1.setInterpolator(new LinearInterpolator());//插补器有没有不影响
                animator1.setDuration(1000);
                animator1.start();
            } else {
                navigation.setBackgroundColor(ContextCompat.getColor(this, R.color.gray_6c));
            }

        } else {
            navigation.setBackgroundColor(ContextCompat.getColor(this, R.color.white));
        }*/

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment fragment = TabFragment.from(item.getItemId()).fragment();
        if (!fragment.isAdded()) {
            ft.add(R.id.content, fragment);
        }
        if (currentMenuId != -1) {
            ft.hide(TabFragment.from(currentMenuId).fragment());
        }
        ft.show(fragment)
                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .commit();

        currentMenuId = item.getItemId();
        return true;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("currentMenuId", currentMenuId);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        navigation.setSelectedItemId(savedInstanceState.getInt("currentMenuId"));
    }

    private enum TabFragment {
        image(R.id.navigation_image, HomeImageFragment.class),
        news(R.id.navigation_ruankao, RuankaoFragment.class),
        newsType(R.id.navigation_news_type, HomeNewsTypeFragment.class),
        widget(R.id.navigation_widget, WidgetFragment.class),
        mine(R.id.navigation_mine, HomeMineFragment.class);

        private Fragment fragment;
        private final int menuId;
        private final Class<? extends Fragment> clazz;

        TabFragment(@IdRes int menuId, Class<? extends Fragment> clazz) {
            this.menuId = menuId;
            this.clazz = clazz;
        }

        @NonNull
        public Fragment fragment() {
            if (fragment == null) {
                try {
                    fragment = clazz.newInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                    fragment = new Fragment();
                }
            }
            return fragment;
        }

        public static TabFragment from(int itemId) {
            for (TabFragment fragment : values()) {
                if (fragment.menuId == itemId) {
                    return fragment;
                }
            }
            return newsType;
        }

        public static void onDestroy() {
            for (TabFragment fragment : values()) {
                fragment.fragment = null;
            }
        }
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }

        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.showToast(this, getString(R.string.press_again_exit));
            exitTime = System.currentTimeMillis();
        } else {
            super.onBackPressed();
            //退出
            AppManager.getInstance().appExit(this);
        }
    }

    @Override
    public void onUpdateInfo(final AppVersion appVersion) {
        new AlertDialog.Builder(this)
                .setTitle("版本更新：" + appVersion.getVersionName())
                .setMessage(appVersion.getUpdateMessage())
                .setCancelable(false)
                .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Uri uri = Uri.parse(appVersion.getApkDownloadUrl());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);

//                        Downloader.getInstance().download(MainActivity.this, appVersion.getApkDownloadUrl(),
//                                new DownloadConfiguration.Builder()
//                                        .setTitle("AtomApp")
//                                        .setVersion(appVersion.getVersionName())
//                                        .build());

//                        getPresenter().downloadApk(appVersion.getApkDownloadUrl());

                    }
                })
                .create()
                .show();
    }

    @Override
    public void onDownloadFinish(File apkFileName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 由于没有在Activity环境下启动Activity,设置下面的标签
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(apkFileName), "application/vnd.android.package-archive");
        startActivity(intent);

    }

    private AlertDialog progressDialog;
    private ProgressCircleView progressCircleView;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onDownloadProgress(int progress) {
        if (progressDialog == null) {
            View view = getLayoutInflater().inflate(R.layout.item_download_apk, null);
            progressCircleView = view.findViewById(R.id.progressView);
            progressDialog = new AlertDialog.Builder(this)
                    .setTitle("正在下载新版本")
                    .setView(view)
                    .setCancelable(false)
                    .create();
            progressDialog.show();
        }
        progressCircleView.setData(progress);

    }

}
